<?php

namespace App\Controllers;
// 创建密钥
use App\Models\UserMsgModel;
use App\Filters\AuthFilter;


class UserController extends BaseController
{
    public function userinfo(){
        $user_id = AuthFilter::getAccessToken($this->request);

        $userMsgModel = new UserMsgModel();

        $data = $userMsgModel->where('id',$user_id)->find()[0];

        return json_encode(['msg'=>'获取个人信息成功','data'=>$data,'code'=>200]);
    }

    public function doUpdateInfo(){
        // $encrypter = \Config\Services::encrypter();

        // 获取当前上下文的request
        $user_id = AuthFilter::getAccessToken($this->request);

        $request = $this->request;
        $input = $request->getPost();
        // 获取数据库模型
        $userMsgModel = new UserMsgModel();

        $res = $userMsgModel->update($user_id,$input) ;
        return  json_encode(['msg'=>'更新成功','code'=>200]);
    }

    public function doUpdatePwd(){
        $encrypter = \Config\Services::encrypter();

        // 获取当前上下文的request
        $user_id = AuthFilter::getAccessToken($this->request);
        // 获取当前上下文的request
        $request = $this->request;
        $input = $request->getPost();
        // 获取数据库模型
        $userMsgModel = new UserMsgModel();
        $user1 = $userMsgModel->where(['id'=>$user_id])->find();
        // 解密旧密码
        $old_password = $encrypter->decrypt(base64_decode($user1[0]['password']));
        if($old_password == $input['old_password']){
            // 加密新密码
            $new_password = base64_encode($encrypter->encrypt($input['new_password']));
            date_default_timezone_set("PRC");
            $data = [
                'password'=>$new_password,
                'updateTime'=>date('Y-m-d H:i:s',time())
            ];
            $res = $userMsgModel->update($user_id,$data) ;
            return  json_encode(['msg'=>'更新成功','code'=>200]);
        }else{
            // 返回的依旧是字符串
            return  json_encode(['msg'=>'更新失败！密码错误','code'=>403]);
        }
    }
}
